﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Security.Cryptography;
using System.Reflection;
using System.Web.Http;
using System.Web.Optimization;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using ERPStore.Web.Extensions;
using ERPStore.Web.Html;
using ERPStore.Web.Routing;

using ERPStore.Extensions;

namespace ERPStore.Web
{
	public class ERPStoreApplication
	{
		static bool m_FailedOnInitialize = false;
		private bool m_IsInitialized = false;
		Exception m_FirstError;

		#region Web Application Events

		public void Start(System.Web.HttpContext ctx)
		{

			/*
			try
			{
				var httpContext = new System.Web.HttpContextWrapper(ctx);
				var executingContext = ERPStore.Configuration.ConfigurationSettings.AppSettings["executingContext"] ?? "Production";
				var ec = (ERPStore.Models.ExecutingContext)Enum.Parse(typeof(ERPStore.Models.ExecutingContext), executingContext, true);

				Initialize(httpContext, ec);
			}
			catch (Exception ex)
			{
				m_FailedOnInitialize = true;
				m_FirstError = ex;
				if (!ctx.Request.IsLocal)
				{
					System.Diagnostics.EventLog.WriteEntry("Application", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
				}
				else
				{
					if (RouteTable.Routes.GetByName("CatchAll") == null)
					{
						RouteTable.Routes.MapERPStoreRoute(
							"CatchAll"
							, "{*catchall}"
							, new { controller = "Home", action = "CatchAll" }
						);
					}
					throw;
				}
			}*/
		}

		public void Stop()
		{
		}


		#endregion

		internal void Initialize(System.Web.HttpContextBase ctx, ERPStore.Models.ExecutingContext executingContext)
		{
			if (m_IsInitialized)
			{
				return;
			}

			ctx.Response.AppendToLog("*************************** Starting ERPStore **********************************");

			ERPStore.GlobalConfiguration.Configuration.HosterName = ERPStore.Configuration.ConfigurationSettings.AppSettings["ERStoreHostName"] ?? "WebApp";
			ERPStore.GlobalConfiguration.Configuration.ExecutingContext = executingContext;

			var section = (System.Web.Configuration.CompilationSection)System.Configuration.ConfigurationManager.GetSection("system.web/compilation");
			ERPStore.GlobalConfiguration.Configuration.DebugEnabled = section.Debug;

			var container = ERPStore.Web.Start.UnityConfig.GetConfiguredContainer(ctx);

			// ERPStore.Web.Start.UnityWebActivator.Start(container);
			// ERPStore.Web.Start.UnityWebApiActivator.Start(container);

			GlobalConfiguration.Configuration.Logger.Info("initialization started");

			if (GlobalConfiguration.Configuration.ExecutingContext == ERPStore.Models.ExecutingContext.Production
				&& GlobalConfiguration.Configuration.DebugEnabled)
			{
				GlobalConfiguration.Configuration.Logger.Notification("Debug enabled in production !");
			}

			GlobalConfiguration.Configuration.Logger.Debug("container initialized");
			GlobalConfiguration.Configuration.Logger.Info("ERPStore ExecutionContext {0}", GlobalConfiguration.Configuration.ExecutingContext);

			ERPStore.Web.Start.SiteConfig.Configure(container, ctx);
			ERPStore.Web.Start.ValidationConfig.Register(container);
			ERPStore.Web.Start.PluginsConfig.Load(container, ctx);

			if (GlobalConfiguration.Configuration.ExecutingContext != ERPStore.Models.ExecutingContext.Preproduction)
			{
				GlobalConfiguration.Configuration.Logger.Debug("Registered services list : ");
				// Show services list
				foreach (var item in container.Registrations)
				{
					GlobalConfiguration.Configuration.Logger.Debug("Service {0} : {1} mappedTo {2}", item.Name, item.RegisteredType, item.MappedToType);
					GlobalConfiguration.Configuration.Logger.Debug("Lifetime : {0}", item.LifetimeManagerType);
				}
			}

			ERPStore.Web.Start.FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			System.Web.Http.GlobalConfiguration.Configure(ERPStore.Web.Start.WebApiConfig.Register);
			ERPStore.Web.Start.RouteConfig.RegisterRoutes(RouteTable.Routes, container);
			ERPStore.Web.Start.MetadataConfig.Configure(container);
			ERPStore.Web.Start.BundleConfig.Register(ctx);

			var eventPublisher = container.Resolve<ERPStore.Services.IEventPublisher>();
			eventPublisher.AsyncPublish(new ERPStore.Events.ApplicationStartedEvent());

			m_IsInitialized = true;
			GlobalConfiguration.Configuration.Logger.Info("initialization completed");
			GlobalConfiguration.Configuration.Logger.Notification("ERPStore for {0} ({1}) in {2} is started context {3} debug {4}", GlobalConfiguration.Configuration.Settings.SiteName, GlobalConfiguration.Configuration.Settings.ApplicationName, System.Environment.MachineName, GlobalConfiguration.Configuration.ExecutingContext, GlobalConfiguration.Configuration.DebugEnabled);
		}

	}
}
